/*
 * Example-app javascript for the navigation and lookup
 * dialogs. See xopus-config for javascript code that
 * is hooked into the editor.
 *
 * Xopus for DITA
 */
/* Lookup utils {{{ */

lookup = 
{
   /**
    * Designed to set the ID on a new (nested) task element together with the
    * task/title/text. Set the lookup on the task/@id. 
    */
  newtext: 
  {
    // do not update the id when typing text in the title field: 
    keep_id : false,


    init: function ()
    {
      document.getElementById('id_field').value = top.dialogArguments.value;
      if (top.dialogArguments.value != '') {
        lookup.newtext.keep_id = true;
      }
      document.getElementById('title_field').focus();
    },


    choose: function (text, id) 
    {
      var text = document.getElementById('title_field').value;
      var id = document.getElementById('id_field').value;
      // TODO improve validation feedback
      if (id != '' && text != '') {
        // Paste text in title element: 
        var node = top.dialogArguments.node;
        if (node) {
          var titleElm = node.selectSingleNode('title');
          titleElm.setTextContent(text);
        }
        top.choose({id: id});
        return true;
      }
      return false;
    },


    onKeyUp: function (event) 
    {
      if (lookup.newtext.keep_id) return true;

      var text = document.getElementById('title_field').value || '';
      var fixed = text.toLowerCase();
      // Strip leading non-IDTOKEN:
      fixed = fixed.replace(/^([\d_]|[^\w])+/g, '');
      // Replace spaces by a dash
      fixed = fixed.replace(/\s+/g, '-');
      // Reduce dashes
      fixed = fixed.replace(/-+/g, '-');
      // Strip non-word or non-dash:
      fixed = fixed.replace(/[^\w-]+/g, '');
      if (fixed == '') {
        fixed = 'id';
      }

      // Check for existing ID in this document
      function recurse_new_id (thisElement, idstring, max) 
      {
        if (max == 300) {
          alert('Not a valid ID; Please enter a valid ID manually. ');
          return idstring;
        }

        var doc = thisElement.getOwnerDocument().getDocumentElement();
        var existingelm = doc.selectSingleNode('//*[@id = "' + idstring + '"]');
        if (existingelm && existingelm != thisElement) {
          var got_num = idstring.match(/\d+$/);
          if (got_num) {
            var num = 1 + parseInt(got_num[0], 10);
            idstring = idstring.replace(/\d+$/, num);
          } else {
            idstring += 2;
          }
          return recurse_new_id(thisElement, idstring, max === undefined ? 0 : max + 1);
        }
        return idstring;
      }

      if (top.dialogArguments.node) {
        var node = top.dialogArguments.node;
        fixed = recurse_new_id(node, fixed);
      }
      document.getElementById('id_field').value = "" + fixed;
    }
  },

 
  chooseReference : function (value)
  {
    top.choose({href:value, scope:'local'});
    return false;
  }, 

  chooseConref : function (value)
  {
    // Take current xml:base into account!
    // XXX I'd rather have this in the dynamic webpage-generating backend code: 
    if (top.dialogArguments) {
      var n = top.dialogArguments.node;
      var d = n.getOwnerDocument().getDocumentElement();
      var base = d.getAttribute('xml:base');
      if (base) {
        // Count slashes after /documents/:
        var up = 0;
        if (base.indexOf('/documents/') != -1) {
          var path = base.substring(base.indexOf('/documents/') + '/documents/'.length);
          up = path.replace(/[^\/]/g, '').length; 
        }
        var prefix = '';
        for (var i = 0; i < up; i++) {
          prefix += '../';
        }
        value = prefix + value;
      }
    }
    top.choose({conref : value});
    return false;
  }, 

  createNewLink : function (id)
  {
    var li = document.createElement('li');
    li.className = "reference";
    var a = document.createElement('a');

    var reference = '#' + id;
    a.setAttribute('href', reference);
    a.setAttribute('value', reference);
    a.innerHTML = reference + " (local reference)";

    if (window.addEventListener) //W3
      a.addEventListener("click", function(){ return lookup.chooseConref(reference);}, true);
    else if (window.attachEvent) //IE
      a.attachEvent("onclick", function(){ return lookup.chooseConref(reference);});

    var parnode = document.getElementById('items');
    parnode.appendChild(li);
    li.appendChild(a);
  },

  checkLocalReferences : function (node)
  {
    var doc = node.getOwnerDocument();
    var name = node.getLocalName();
    var docid = doc.getDocumentElement().getAttribute("id")
    var similarnodes = doc.selectNodes("//*[local-name() = '"+name+"' and @id]");
    for (var i = 0; i < similarnodes.getLength(); i++)
    {
      var similarnode = similarnodes.item(i);
      var id = docid + "/" + similarnode.getAttribute('id');
      var fullid = doc.getDocumentURI().substring(doc.getDocumentURI().indexOf('?fileId=') + 8) + "#" + id;
      var link = document.getElementById(fullid);
      if (link)
      {
        link.setAttribute('href', "#" + id);
        link.setAttribute('value', "#" + id);
        link.innerHTML = "#" + id ;
        link.parnodeNode.innerHTML += " (local reference)"
      }
      else
      {
        lookup.createNewLink(id);
      }
    }
  }, 

  initConref: function ()
  {
    var elname = document.getElementById("elname");
    elname.value = top.dialogArguments.node.getLocalName();
    if (elname.value == "")
      document.getElementById("searchform").submit();

    return lookup.checkLocalReferences(top.dialogArguments.node);
  }

};

/* }}} */
/* Navigation utils {{{ */

MapNavigation = 
{
  currentID: false,

  openDocument: function (anchor, url) {
    this.clearSelection();
    var row = anchor.parentNode.parentNode;
    row.className = "navigation-file-title-currentrow";
    this.currentID = row.id;

    var editor = parent.document.getElementById('xopusFrame').contentWindow.Editor;
    if (editor) {
      editor.setURL(url);
    }
    return false;
  },

  clearSelection: function () {
    if (this.currentID) {
      var old = document.getElementById(this.currentID);
      if (old)
        old.className = undefined;
    }
  }
}


CreateDocument = 
{
  toggleDialog: function () {
    var e = document.getElementById('createDocumentForm');
    if (e.style.display == 'block')
      e.style.display = 'none';
    else   {
      e.style.display = 'block';

      var f = document.getElementById('name');
      var id_field = document.getElementById('id');
      var id;

      if (f.value == "" && id_field.value == "") {
          id = new UUID(); // see uuid.js
          id_field.value = "id" + id.toString();
      }
      f.focus();
    }
    return false;
  },

  cancelDialog: function () {
    var e = document.getElementById('createDocumentForm');
    e.style.display = 'none';
    return true; /* reset's form content */
  },

  submitHandler : function () 
  {
    function updateUI(input, isValid) {
      var c = input.parentNode.className;
      input.parentNode.className = c.replace(/(\svalid-field)-(true|false)/, 
                                          isValid ? "$1-true" : "$1-false");
      return !!isValid;
    };

    function checkValue(inputID) {
      var e = document.getElementById(inputID);
      return updateUI(e, e.value != "");
    }

    function checkValues() {
      var rval = true;
      for (var i = 0; i < arguments.length; i++) {
        rval = checkValue(arguments[i]) && rval;
      }
      return rval;
    }

    return checkValues('name', 'id', 'type');
  }, 

  removeNewDoc: function () {
    this.cancelDialog();
    // XXX Really ought to do a reload without the newdoc query string
    // argument:
    var e = document.getElementById('createDocumentNewDoc');
    e.style.display = 'none';
  },

  /** Save the checkbox setting in a cookie... @see toggleDialog */
  saveUseSample: function (is_checked) {
    var monthInSec = 60*60*24*31;
    document.cookie = "dita_createform_use_sample_v1="
        + (is_checked ? '1':'0') + ";max-age=" + monthInSec; 
  }
}

/* }}} */
